import 'package:aio/aio.dart';

import '../../../config/app_data_config.dart';
import 'attendances.dart';

///打卡记录
class ClockinInfo extends BaseBean {
  MyGroupBcInfo? GroupBcInfo = null; //打卡班组

  //fixme 原班次的时间格式
  // "OnWorkTime": "08:00",
  // "OffWorkTime": "17:00"
  //fixme 这里返回的时间格式
  // "OnWorkTime": "2022-04-07 8:00:00",
  // "OffWorkTime": "2022-04-07 17:00:00"
  //打卡班次;服务器只返回班次开始时间和结束时间。
  // "Attendance": {
  // "AttendanceId": 0,
  // "WorkTypeName": null,
  // "OnWorkTime": "2022/8/30 8:00:00",
  // "OffWorkTime": "2022/8/30 17:30:00"
  // },
  MyAttendances? Attendance = null;
  MyAttendances? _Attendance = null;

  ///获取班次；补全班次的信息。主要补全班次名称。
  MyAttendances? getAttendance() {
    if (_Attendance != null) {
      return _Attendance;
    }
    // print(
    //     "1====================================================================id:${Attendance?.AttendanceId}\t${Attendance?.WorkTypeName}");
    if (isEmpty(Attendance?.AttendanceId) ||
        isEmpty(Attendance?.WorkTypeName)) {
      GroupBcInfo?.Attendances?.forEach((element) {
        if (_Attendance == null) {
          //print("2===============================================================start:${Attendance?.start()}\t${element?.start()}\tend:${Attendance?.end()}\t${element?.end()}");
          //fixme 以开始时间和结束时间，同时为标准。
          if (Attendance?.start() == element?.start() &&
              Attendance?.end() == element?.end()) {
            _Attendance = element;
          }
        }
      });
      if (_Attendance != null) {
        return _Attendance;
      } else {
        GroupBcInfo?.Attendances?.forEach((element) {
          if (_Attendance == null) {
            //print("3===============================================================start:${Attendance?.start()}\t${element?.start()}\tend:${Attendance?.end()}\t${element?.end()}");
            //fixme 以开始时间为标准。
            if (Attendance?.start() == element?.start()) {
              _Attendance = element;
            }
          }
        });
      }
    }
    //print("4====================================================================Attendance:${Attendance?.WorkTypeName}");
    if (_Attendance != null) {
      return _Attendance;
    } else {
      return Attendance;
    }
  }

  ///上班
  String? OnWorkTime =
      null; //打卡时间 ；时间格式：yyyy-MM-dd HH:mm:ss 如：2022-08-01 15:01:14
  String? OnWorkAdress = null; //打卡地址
  String getOnWorkAdress() {
    if (isEmpty(OnWorkAdress) && !isOnWorkPhone) {
      var FactoryName = AppDataConfig.getFactory()?.FactoryName ?? "";
      return FactoryName;
    }
    return OnWorkAdress ?? "";
  }

  bool isOnWorkField = false; //是否外勤打卡。（是否外勤签到）
  String? OnWorkImageUrl = null; //打卡图片
  bool isOnWorkPhone = false; //是否手机打卡。true 手机打卡；false 电脑打卡
  bool isLate = false; //是否迟到
  //手动计算是否迟到
  bool islate() {
    return isLate; //目前还是用服务器的。
    // _onWorkTime();
    // return Attendance?.isLate(_OnWorkTime) ?? isLate;
  }

  ///判断是否正在上班
  bool isOnWork() {
    //OnWorkTime:2022-04-07 9:07:00	2022-08-04 13:09:08
    //print("=====================================================================OnWorkTime:$OnWorkTime\tOffWorkTime:$OffWorkTime");
    if (isNotEmpty(OnWorkTime) && isEmpty(OffWorkTime)) {
      return true;
    }
    return false;
  }

  ///判断是否已经下班打卡;(主要判断当天是否已经下班打过卡)
  bool isOffWork() {
    if (isNotEmpty(OffWorkTime)) {
      _offWorkTime();
      if (_OffWorkTime != null) {
        var now = DateTime.now();
        var difference = now.difference(_OffWorkTime!);
        var inHours = difference.inHours.abs();
        //print("=======================================_OffWorkTime:$_OffWorkTime\tinHours:$inHours");
        if (inHours <= 6) {
          //print("===============================================================已经下班打卡");
          return true;
        }
      }
    }
    return false;
  }

  ///判断当天是否有打过卡。true 当天打过卡；false 当天都没有打卡记录
  bool isWork() {
    if (isOnWork()) {
      return true;
    }
    if (isOffWork()) {
      return true;
    }
    return false;
  }

  ///下班
  String? OffWorkTime = null; //打卡时间
  String? OffWorkAdress = null; //打卡地址
  String getOffWorkAdress() {
    if (isEmpty(OffWorkAdress) && !isOffWorkPhone) {
      var FactoryName = AppDataConfig.getFactory()?.FactoryName ?? "";
      return FactoryName;
    }
    return OffWorkAdress ?? "";
  }

  bool isOffWorkField = false; //是否外勤打卡。
  String? OffWorkImageUrl = null; //打卡图片
  bool isOffWorkPhone = false; //是否手机打卡。true 手机打卡；false 电脑打卡
  bool isLeaveEarly = false; //是否早退
  //手动计算是否早退
  bool isleaveEarly() {
    return isLeaveEarly; //目前还是用服务器的。
    // _offWorkTime();
    // return Attendance?.isLeaveEarly(_OffWorkTime) ?? isLate;
  }

  DateTime? _OnWorkTime = null;

  ///获取开始打卡日期
  DateTime? _getOnWorkDateTime() {
    _onWorkTime();
    return _OnWorkTime;
  }

  DateTime? _AttendanceOnWorkTime = null;

  // "Attendance": {
  // "AttendanceId": 0,
  // "WorkTypeName": null,
  // "OnWorkTime": "2021/9/26 8:00:00",
  // "OffWorkTime": "2021/9/26 17:00:00"
  // },
  ///fixme 获取唯一键；打卡记录以班次的开始时间为标准。
  DateTime? getKeyDateTime() {
    String? OnWorkTime = Attendance?.OnWorkTime;
    if (_AttendanceOnWorkTime == null && isNotEmpty(OnWorkTime)) {
      try {
        String? OnWorkTime2 = OnWorkTime?.replaceAll("/", "-");
        _AttendanceOnWorkTime = DateTimeUtils.stringToDateTime(OnWorkTime2,
            format: "yyyy-MM-dd HH:mm");
      } catch (e) {
        print("上班时间_onWorkTime()方法解析异常：$e");
      }
    }
    if (_AttendanceOnWorkTime == null) {
      return _getOnWorkDateTime(); //以防万一。
    }
    return _AttendanceOnWorkTime;
  }

  _onWorkTime() {
    if (_OnWorkTime == null && isNotEmpty(OnWorkTime)) {
      try {
        String? OnWorkTime2 = OnWorkTime?.replaceAll("/", "-");
        _OnWorkTime = DateTimeUtils.stringToDateTime(OnWorkTime2,
            format: "yyyy-MM-dd HH:mm");
      } catch (e) {
        print("上班时间_onWorkTime()方法解析异常：$e");
      }
    }
  }

  ///上班时间格式
  String formatOnWorkTime({String format = "MM-dd HH:mm"}) {
    try {
      _onWorkTime();
      return DateTimeUtils.format(_OnWorkTime, format: format);
    } catch (e) {
      print("上班时间格式解析异常：$e");
    }
    return OnWorkTime ?? "";
  }

  DateTime? _OffWorkTime = null;

  _offWorkTime() {
    if (_OffWorkTime == null && isNotEmpty(OffWorkTime)) {
      try {
        String? OffWorkTime2 = OffWorkTime?.replaceAll("/", "-");
        _OffWorkTime = DateTimeUtils.stringToDateTime(OffWorkTime2,
            format: "yyyy-MM-dd HH:mm");
      } catch (e) {
        print("下班时间_offWorkTime()方法解析异常：$e");
      }
    }
  }

  ///下班时间格式
  String formatOffWorkTime({String format = "MM-dd HH:mm"}) {
    try {
      _offWorkTime();
      return DateTimeUtils.format(_OffWorkTime, format: format);
    } catch (e) {
      print("下班时间格式解析异常：$e");
    }
    return OffWorkTime ?? "";
  }

  @override
  fromJson(Map<String, dynamic> json) {
    // TODO: implement fromJson
    GroupBcInfo = setGenericFromJson(json, 'GroupBcInfo', MyGroupBcInfo(), "");
    Attendance = setGenericFromJson(json, 'Attendance', MyAttendances(), "");
    OnWorkTime = json["OnWorkTime"]?.toString();
    OnWorkAdress = json["OnWorkAdress"]?.toString();
    isOnWorkField = json["isOnWorkField"] ?? false;
    OnWorkImageUrl = json["OnWorkImageUrl"]?.toString();
    isLate = json["isLate"] ?? false;
    isOnWorkPhone = json["isOnWorkPhone"] ?? false;

    ///下班
    OffWorkTime = json["OffWorkTime"]?.toString();
    OffWorkAdress = json["OffWorkAdress"]?.toString();
    isOffWorkField = json["isOffWorkField"] ?? false;
    OffWorkImageUrl = json["OffWorkImageUrl"]?.toString();
    isLeaveEarly = json["isLeaveEarly"] ?? false;
    isOffWorkPhone = json["isOffWorkPhone"] ?? false;
  }

  @override
  instance() {
    return ClockinInfo();
  }

  @override
  Map<String, dynamic> toJson() {
    var map = <String, dynamic>{};
    map["GroupBcInfo"] = GroupBcInfo;
    map["Attendance"] = Attendance;
    map["OnWorkTime"] = OnWorkTime;
    map["OnWorkAdress"] = OnWorkAdress;
    map["isOnWorkField"] = isOnWorkField;
    map["OnWorkImageUrl"] = OnWorkImageUrl;
    map["isLate"] = isLate;
    map["isOnWorkPhone"] = isOnWorkPhone;

    ///下班
    map["OffWorkTime"] = OffWorkTime;
    map["OffWorkAdress"] = OffWorkAdress;
    map["isOffWorkField"] = isOffWorkField;
    map["OffWorkImageUrl"] = OffWorkImageUrl;
    map["isLeaveEarly"] = isLeaveEarly;
    map["isOffWorkPhone"] = isOffWorkPhone;
    return map;
  }
}

///个人工资结算(个人)
class WagePerson extends BaseBean {
  String PersonCode = ""; //fixme NC人员编号(员工工号)
  String PersonName = ""; //人员名称
  String? Takeamount = null; //实得金额
  String? Compensationpayable = null; //赔偿金额
  String? Delaypenalty = null; //推迟罚金。
  String? Amountoftime = null; //计时金额
  String? Transferthesubsidies = null; //调动补贴
  String? Pieceworkamount = null; //计件金额,计件工资
  String? Qualityawardamount = null; //质量奖金额
  String? Processingrefund = null; //审核退款
  String? Energyconsumption = null; //能耗奖赔。
  String? Otherpunishment = null; //其他奖罚

  @override
  fromJson(Map<String, dynamic> json) {
    // TODO: implement fromJson
    PersonCode = json["PersonCode"]?.toString() ?? "";
    PersonName = json["PersonName"]?.toString() ?? "";
    Takeamount = json["Takeamount"]?.toString() ?? "";
    Compensationpayable = json["Compensationpayable"]?.toString();
    Delaypenalty = json["Delaypenalty"]?.toString() ?? "";
    Amountoftime = json["Amountoftime"]?.toString() ?? "";
    Pieceworkamount = json["Pieceworkamount"]?.toString() ?? "";
    Transferthesubsidies = json["Transferthesubsidies"]?.toString() ?? "";
    Qualityawardamount = json["Qualityawardamount"]?.toString();
    Processingrefund = json["Processingrefund"]?.toString();
    Energyconsumption = json["Energyconsumption"]?.toString() ?? "";
    Otherpunishment = json["Otherpunishment"]?.toString() ?? "";
  }

  @override
  instance() {
    return WagePerson();
  }

  @override
  Map<String, dynamic> toJson() {
    var map = <String, dynamic>{};
    map["PersonCode"] = PersonCode;
    map["PersonName"] = PersonName;
    map["Takeamount"] = Takeamount;
    map["Compensationpayable"] = Compensationpayable;
    map["Delaypenalty"] = Delaypenalty;
    map["Amountoftime"] = Amountoftime;
    map["Pieceworkamount"] = Pieceworkamount;
    map["Transferthesubsidies"] = Transferthesubsidies;
    map["Qualityawardamount"] = Qualityawardamount;
    map["Processingrefund"] = Processingrefund;
    map["Energyconsumption"] = Energyconsumption;
    map["Otherpunishment"] = Otherpunishment;
    return map;
  }
}

///个人工资结算(班次)
class WageShift extends BaseBean {
  String WorkTypeName = ""; //": "晚班", 班次名称
  String OnWorkTime = ""; //": "18:30", 上班开始时间
  String OffWorkTime = ""; //": "02:30" 下班时间
  String Piecesrequired = ""; //应领用片数(片)
  String Originalpieces = ""; //实际使用原片数(片)
  String Originalfilmsusedmultiple = ""; //多领用原片数(片)
  String Multioriginalfilmarea = ""; //多领用原片面积(平米)

  @override
  fromJson(Map<String, dynamic> json) {
    // TODO: implement fromJson
    WorkTypeName = json["WorkTypeName"]?.toString() ?? "";
    OnWorkTime = json["OnWorkTime"]?.toString() ?? "";
    OffWorkTime = json["OffWorkTime"]?.toString() ?? "";
    Piecesrequired = json["Piecesrequired"]?.toString() ?? "";
    Originalpieces = json["Originalpieces"]?.toString() ?? "";
    Originalfilmsusedmultiple = json["Originalfilmsusedmultiple"] ?? "";
    Multioriginalfilmarea = json["Multioriginalfilmarea"] ?? "";
  }

  @override
  instance() {
    return WageShift();
  }

  @override
  Map<String, dynamic> toJson() {
    var map = <String, dynamic>{};
    map["WorkTypeName"] = WorkTypeName;
    map["OnWorkTime"] = OnWorkTime;
    map["OffWorkTime"] = OffWorkTime;
    map["Piecesrequired"] = Piecesrequired;
    map["Originalpieces"] = Originalpieces;
    map["Originalfilmsusedmultiple"] = Originalfilmsusedmultiple;
    map["Multioriginalfilmarea"] = Multioriginalfilmarea;
    return map;
  }
}

///个人工资结算(当日补片)
class WagePatch extends BaseBean {
  String PatchNum = ""; //当日补片(片)
  String Area = ""; //面积
  String Amount = ""; //金额
  String Perimeter = ""; //周长
  String Weight = ""; //重量

  @override
  fromJson(Map<String, dynamic> json) {
    // TODO: implement fromJson
    PatchNum = json["PatchNum"]?.toString() ?? "";
    Area = json["Area"]?.toString() ?? "";
    Amount = json["Amount"]?.toString() ?? "";
    Perimeter = json["Perimeter"]?.toString() ?? "";
    Weight = json["Weight"]?.toString() ?? "";
  }

  @override
  instance() {
    return WagePatch();
  }

  @override
  Map<String, dynamic> toJson() {
    var map = <String, dynamic>{};
    map["PatchNum"] = PatchNum;
    map["Area"] = Area;
    map["Amount"] = Amount;
    map["Perimeter"] = Perimeter;
    map["Weight"] = Weight;
    return map;
  }
}

///个人工资结算(当日产量)
class WageProduction extends BaseBean {
  String ProductionNum = ""; //当日产量(片)
  String Area = ""; //面积
  String Amount = ""; //金额
  String Perimeter = ""; //周长
  String Weight = ""; //重量

  @override
  fromJson(Map<String, dynamic> json) {
    // TODO: implement fromJson
    ProductionNum = json["ProductionNum"]?.toString() ?? "";
    Area = json["Area"]?.toString() ?? "";
    Amount = json["Amount"]?.toString() ?? "";
    Perimeter = json["Perimeter"]?.toString() ?? "";
    Weight = json["Weight"]?.toString() ?? "";
  }

  @override
  instance() {
    return WageProduction();
  }

  @override
  Map<String, dynamic> toJson() {
    var map = <String, dynamic>{};
    map["ProductionNum"] = ProductionNum;
    map["Area"] = Area;
    map["Amount"] = Amount;
    map["Perimeter"] = Perimeter;
    map["Weight"] = Weight;
    return map;
  }
}

///工资结算
class WageSettlement extends BaseBean {
  WageProduction? wageProduction = null; //(当日产量)
  WagePatch? wagePatch = null; //当日补片
  List<WageShift>? wageShift = null; //班次
  List<WagePerson>? wagePersons = null; //个人工资

  @override
  fromJson(Map<String, dynamic> json) {
    // TODO: implement fromJson
    wageProduction =
        setGenericFromJson(json, "wageProduction", WageProduction(), "");
    wagePatch = setGenericFromJson(json, "wagePatch", WagePatch(), "");
    wageShift =
        setGenericFromJson(json, "wageShift", <WageShift>[], WageShift());
    wagePersons =
        setGenericFromJson(json, 'wagePersons', <WagePerson>[], WagePerson());
  }

  @override
  instance() {
    return WageSettlement();
  }

  @override
  Map<String, dynamic> toJson() {
    var map = <String, dynamic>{};
    map["wageProduction"] = wageProduction;
    map["wagePatch"] = wagePatch;
    map["wageShift"] = wageShift;
    map["wagePersons"] = wagePersons;
    return map;
  }
}

///工资结算请求参数（签退接口会返回）
// {
// "MsgCode": "102",
// "MsgDetail": null,
// "Data": {
// "code": "102",
// "factoryId": 1,
// "groupId": "2",
// "workStartTime": "2022-08-09 18:30:00",
// "AccDate": "2022-08-09 0:00:00",
// "workEndTime": "2022-08-10 2:30:00"
// }
// }
class WageField extends BaseBean {
  String code = "102"; //102 跳转到当日结算 103跳转到 本次结算
  String factoryId = ""; //工厂id
  String groupId = ""; //班组id
  String workStartTime = ""; //班次开始时间 格式 yyyy-MM-dd HH:mm:ss
  String AccDate = ""; //班次开始时间，日期部分 yyyy-MM-dd
  String workEndTime = ""; //班次结束时间 格式 yyyy-MM-dd HH:mm:ss

  WageField() {
    factoryId = AppDataConfig.getFactory()?.FactoryId ?? "";
  }

  @override
  fromJson(Map<String, dynamic> json) {
    // TODO: implement fromJson
    code = json["code"]?.toString() ?? "";
    factoryId = json["factoryId"]?.toString() ?? "";
    groupId = json["groupId"]?.toString() ?? "";
    workStartTime = json["workStartTime"]?.toString() ?? "";
    AccDate = json["AccDate"]?.toString() ?? "";
    workEndTime = json["workEndTime"]?.toString() ?? "";
  }

  @override
  instance() {
    return WageField();
  }

  @override
  Map<String, dynamic> toJson() {
    var map = <String, dynamic>{};
    map["code"] = code;
    map["factoryId"] = factoryId;
    map["groupId"] = groupId;
    map["workStartTime"] = workStartTime;
    map["AccDate"] = AccDate;
    map["workEndTime"] = workEndTime;
    return map;
  }
}
